package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired
    ShoppingCartMapper shoppingCartMapper;

    @Autowired
    DishMapper dishMapper;

    @Autowired
    SetmealMapper setmealMapper;

    /**
     * 添加购物车商品
     * @param shoppingCartDTO
     */
    public void addSC(ShoppingCartDTO shoppingCartDTO) {
        //获取当前用户操作的id
        Long userId = BaseContext.getCurrentId();
        //判断要添加的商品在购物车中是否存在
        ShoppingCart shoppingCart = shoppingCartMapper.shopQuery(shoppingCartDTO);
        // 如果已经存在,则只需要数量加1,然后再重新修改数据库
        if(shoppingCart != null){   //shoppingCart != null
            shoppingCart.setNumber(shoppingCart.getNumber()+1);
            shoppingCart.setUserId(userId);
            shoppingCartMapper.update(shoppingCart);
        }else {   //shoppingCart == null
            shoppingCart = new ShoppingCart();
            shoppingCart.setUserId(userId);
            if (shoppingCartDTO.getDishId() != null ){//如果不存在,则判断添加的是菜品,还是套餐
                //如果是菜品,则根据传递过来的菜品id查询出菜品数据,再插入购物车
                Dish dish = dishMapper.statusQuery(shoppingCartDTO.getDishId());
                BeanUtils.copyProperties(dish,shoppingCart);
                shoppingCart.setAmount(dish.getPrice());
                shoppingCart.setDishId(dish.getId());
            }else {
                //如果是套餐,则根据传递过来的套餐id查询出套餐数据,再插入购物车
                Setmeal setmeal = setmealMapper.getById(shoppingCartDTO.getSetmealId());
                BeanUtils.copyProperties(setmeal,shoppingCart);
                shoppingCart.setAmount(setmeal.getPrice());
                shoppingCart.setSetmealId(setmeal.getId());
            }
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setNumber(1);
            shoppingCart.setDishFlavor(shoppingCartDTO.getDishFlavor());
            shoppingCartMapper.insert(shoppingCart);
        }

    }

    @Override
    public List<ShoppingCart> showShoppingCart() {
        Long userId = BaseContext.getCurrentId();
        List<ShoppingCart> list = shoppingCartMapper.shopQuery01(userId);
        return list;
    }

    /**
     * 清空购物车
     */
    public void cleanShoppingCart() {
        Long userId = BaseContext.getCurrentId();
        shoppingCartMapper.deleteByUserId(userId);
    }
}
